/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, Form, Popconfirm, Table, Tabs} from 'antd';

import FormBase from '../../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import DescGroup from "../../../../components/DescriptionGroup";
import ViewTitle from "../../../../components/ViewTitle";
import notify from "../../../../components/NotificationExtra";
import styles from "../../../index.less";
import {ModalView} from "antd-extra";
import ModalProdDetail from "../../../sales/modal/ModalProdDetail";
import ModalOutboundLotDetail from "../../../store/modal/ModalOutboundLotDetail";
import ModalCreateOutboundLot from "../../../store/modal/ModalCreateOunboundLot";

import ModalCreateOrEditPaymentRecord from "../../modal/ModalCreateOrEditPaymentRecord";

const {TabPane} = Tabs;
moment.locale('zh-cn');
const table = 'SalesOrder';
@Form.create()
@connect(({
            user,
            global,
            dynamicLabel,
            sales,
            finance,
            store
          }) => ({...user, ...finance, ...store, ...sales, ...dynamicLabel, ...global}))
export default class ModalSalesOrderPayDetail extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {values, dispatch, treeId} = this.props;

    const {code} = values;
    dispatch && dispatch({
      type: 'sales/findOne',
      payload: {code}
    });
    // if (isReview) return;

    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table}
    });
    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table: 'OutboundOrder'}
    });
    this.props.dispatch({
      type: 'finance/findRecordMany',
      payload: {orderCode: code, table: 'Payment', treeId: treeId}
    });
    this.onDataLoad().then(response => {
      this.setState(response);
    });
  }

  async onDataLoad() {
    const {values, dispatch} = this.props;
    const {code} = values;
    const lotRes = await dispatch({
      type: 'store/findOutboundLots',
      payload: {orderCode: code}
    });
    let _shippingFee = 0;
    const {result = []} = lotRes;
    _.map(result, lot => {
      const {shippingFee = 0} = lot;
      _shippingFee += shippingFee;
    });
    return {lots: lotRes.result, shippingFee: _shippingFee};
  }

  prodTableCol() {
    const {isFinance = false, isPayReview} = this.props;
    return [
      {
        title: "品名编号", dataIndex: 'prodName', key: 'prodName', render: (value, record) => {
          const {prodCode} = record;
          return this.getProductionElement(prodCode, value);
        }
      },
      {title: "品名", key: "prodName", dataIndex: "prodName"},
      {title: "编号", key: "prodCode", dataIndex: "prodCode"},
      {title: "重量（KG)", key: "count", dataIndex: "count"},
      {title: "单价", key: "price", dataIndex: "price"},
      {title: "标签", key: "label", dataIndex: "label"},
      {title: "发货方式", key: "deliverWay", dataIndex: "deliverWay"},
      {title: "包装", key: "pkg", dataIndex: "pkg"},
      {title: "包装费用", key: "pkgFee", dataIndex: "pkgFee"},
      {
        title: "出货数量", key: "outboundCount", dataIndex: "outboundCount", render: (value, record) => {
          const {lots = []} = this.state;
          const {_code} = record;
          let count = 0;
          _.map(lots, lot => {
            const {code, outboundCount} = lot;
            if (code === _code) {
              count += outboundCount;
            }
          });
          return <div>{count}</div>;
        }
      },
      {title: "劳务费用", key: "laborFee", dataIndex: "laborFee"},
      {title: "劳务扣税点", key: "taxDeductionPointForLaborCosts", dataIndex: "taxDeductionPointForLaborCosts"},
      {
        title: "开票日期", key: "invoicingDate", dataIndex: "invoicingDate", render: value => {
          return value ? <div>{moment(value).format("yyyy-MM-DD")}</div> : <div>未开票</div>;
        }
      },
      {
        title: "操作", key: 'opt', dataIndex: "opt", render: (value, record) => {
          return <span>
            <a style={{marginRight: '6px'}} onClick={() => {
              ModalView.open(ModalProdDetail, {
                title: '商品详情',
                width: '1580px'
              }, {
                values: record,
                callback: data => {

                }
              });
            }}>详情</a>
            {<a disabled={record.deliverWay !== '直发' || isFinance || isPayReview} style={{marginRight: '6px'}}
                onClick={() => {
                  console.log('recordd', record);
                  const {style, salesOrder = {}, _notify, outboundLots = [], isReview, cols = 4} = this.props;

                  ModalView.open(ModalCreateOutboundLot, {
                    title: '创建出货记录',
                    width: '1080px'
                  }, {
                    record,
                    callback: payload => {
                      payload.orderCode = salesOrder.code;
                      payload._code = record._code;
                      payload.division = salesOrder.division;
                      this.props.dispatch({
                        type: 'store/createOutboundLot',
                        payload
                      }).then(res => {
                        this.requestReturn(res);
                        this.componentDidMount();
                      });
                    }
                  });

                }}>一键出货</a>

            }
          </span>;
        }
      }
    ];
  }

  lotCols() {
    const model = this.props['OutboundOrderModel'];

    const temp = this.getOutboundLotCols(model);
    temp.push(
      {
        title: '操作', key: 'opt', dataIndex: "opt", render: (value, values) => {
          return <a onClick={() => {
            ModalView.open(ModalOutboundLotDetail, {
              title: '出库记录详情',
              width: '920px',
              maskClosable: false
            }, {
              values,
              isEdit: false,
              callback: (result) => {

              }
            });
          }} style={{marginRight: '6px'}}>详情</a>;
        }
      }
    );
    return temp;
  }

  onCreateOrEditPay = record => {
    const title = record ? '编辑记录' : "创建记录";
    const type = record ? "finance/updateRecord" : "finance/createRecord";
    const {customers, vendors, treeId, values} = this.props;
    ModalView.open(ModalCreateOrEditPaymentRecord,
      {
        title,
        width: '1080px'
      }, {
        record, table, customers, vendors, order: values,
        callback: (payload) => {
          payload.table = "Payment";
          payload.divison = values.divison;
          payload.code = record ? record.code : 'FIN' + new Date().valueOf();
          payload.treeId = treeId;
          payload.treeName = this.props.title;

          this.props.dispatch({
            type,
            payload
          }).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
        }
      });
  };

  financeCols() {
    const {isFinance, isPayReview} = this.props;
    return [
      {title: "户名", dataIndex: '_accountName', key: '_accountName'},
      {title: "开户行", dataIndex: 'openingBank', key: 'openingBank'},
      {title: "支出方式", dataIndex: 'payWay', key: 'payWay'},
      {title: "支出金额", dataIndex: 'paymentAmount', key: 'paymentAmount'},
      {
        title: "付款日期", dataIndex: 'date', key: 'date', render: value => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      },
      {
        title: "操作", dataIndex: 'opt', key: 'opt', render: (value, record) => {
          const {code} = record;
          return <span>
                      {
                        <a style={{marginRight: '6px'}}
                           onClick={() => {
                             this.onCreateOrEditPay(record);
                           }}
                           disabled={!isFinance}
                        >编辑</a>
                      }
            {<Popconfirm
              title="确认删除"
              onConfirm={() => {
                this.props.dispatch({
                  type: "finance/deleteRecord",
                  payload: {table: 'Payment', code}
                }).then(res => {
                  this.requestReturn(res);
                  this.componentDidMount();
                });
              }}
              okText="是"
              cancelText="否"
            >
              <a disabled={!isFinance}>删除</a>
            </Popconfirm>}
           </span>;
        }
      }

    ];
  }

  render() {
    const {
      style,
      salesOrder = {},
      isPayReview = false,
      cols = 4, reviewPath,
      isFinance = false,
      PaymentRecords = []
    } = this.props;
    const {lots, shippingFee, _notify} = this.state;

    if (_notify) {
      notify(_notify);
    }
    const model = this.props[`${table}Model`];
    if (!model || !salesOrder) return <div></div>;
    const _labels = _.filter(model, (item, key) => {
      if (key !== 'labels' && _.includes(item.enableArea, 'detail')) {
        item.key = key;
        return item;
      }
    });

    const _values = _.cloneDeep(salesOrder);
    _values.shippingFee = shippingFee;
    _.map(_labels, item => {
      const {_type, key} = item;
      if (_type.toLowerCase() === 'switch') {
        _values[key] = _values[key] ? "是" : "否";
      }
      if (_type.toLowerCase() === 'date') {
        _values[key] = _values[key] ? moment(_values[key]).format('YYYY-MM-DD') : '';
      }
    });


    return (
      <div style={{...style}}>
        <Tabs defaultActiveKey="1">
          <TabPane tab="订单" key="1">
            <ViewTitle
              title={'订单信息'}
              level={1}
              actions={[
                isPayReview && <Button type="primary" onClick={() => {
                  const {code} = salesOrder;
                  if (lots.length > 0) {
                    notify({type: "error", message: "已有出库记录，请修改出库后再进行审批修改！"});
                    return;
                  }
                  if (payRecords.length > 0) {
                    notify({type: "error", message: "已有付款记录，请修改付款后再进行审批修改！"});
                    return;
                  }

                  const _payload = {code};
                  _payload[reviewPath] = "同意";
                  console.log('_payload', _payload);
                  isPayReview && this.props.dispatch({
                    type: 'sales/payReview',
                    payload: _payload
                  }).then(res => {
                    this.props.callback();
                    this.componentDidMount();
                  });

                }}>同意</Button>,
                isPayReview && <Button type={'danger'} onClick={() => {
                  const {code} = salesOrder;

                  if (lots.length > 0) {
                    notify({type: "error", message: "已有出库记录，请修改出库后再进行审批修改！"});
                    return;
                  }
                  if (payRecords.length > 0) {
                    notify({type: "error", message: "已有付款记录，请修改付款后再进行审批修改！"});
                    return;
                  }
                  const _payload = {code};
                  _payload[reviewPath] = "驳回";
                  console.log('_payload', _payload);
                  isPayReview && this.props.dispatch({
                    type: 'sales/payReview',
                    payload: _payload
                  }).then(res => {
                    this.props.callback();
                    this.componentDidMount();
                  });
                }}>驳回</Button>
              ]}
            ></ViewTitle>
            <DescGroup
              {...{
                labels: _labels,
                values: _values,
                size: 'small',
                column: cols
              }}
            ></DescGroup>
            {/*<div>备注</div>*/}
            {/*<div>{salesOrder.memo}</div>*/}
            <ViewTitle
              title={'商品信息'}
            ></ViewTitle>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.prodTableCol()}
              dataSource={salesOrder.prods}
              scroll={{x: true}}
              pagination={true}
            ></Table>
          </TabPane>
          <TabPane tab={'出货'} key="2">
            {<ViewTitle
              title={'出库单信息'}
              level={1}
            ></ViewTitle>}
            {
              <Table
                className={styles.antTable}
                bordered={true}
                columns={this.lotCols()}
                dataSource={lots}
                scroll={{x: true}}
                pagination={true}
              ></Table>
            }
          </TabPane>
          <TabPane tab={'付款'} key="3">
            {<ViewTitle
              title={'付款记录'}
              level={1}
              actions={isFinance && <Button type={"primary"} onClick={() => {
                this.onCreateOrEditPay();
              }}>添加</Button>}
            ></ViewTitle>}
            {
              <Table
                className={styles.antTable}
                bordered={true}
                columns={this.financeCols()}
                dataSource={PaymentRecords}
                scroll={{x: true}}
                pagination={true}
              ></Table>
            }
          </TabPane>
        </Tabs>
      </div>
    );
  }
}

